package com.liujit.bms.app.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujit.bms.app.domain.model.BlogMember;
import com.liujit.bms.app.domain.params.BlogMemberParams;
import com.liujit.bms.app.mapper.BlogMemberMapper;
import com.liujit.bms.app.service.BlogMemberService;
import com.liujit.common.constants.GlobalConstant;
import com.liujit.common.exception.DataNotFoundException;
import com.liujit.common.utils.DozerConvertor;
import com.liujit.minio.domain.FileUploadResult;
import com.liujit.minio.service.FileService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @Description 博客会员Service实现类
 * @Author liujun
 * @Date 2021-07-13 11:10:50
 */
@RequiredArgsConstructor
@Service
public class BlogMemberServiceImpl extends ServiceImpl<BlogMemberMapper, BlogMember> implements BlogMemberService {

    private final FileService fileService;

    @Override
    public BlogMember save(BlogMemberParams params) {
        BlogMember entity = DozerConvertor.convertor(params, BlogMember.class);
        if (params.getId() == null) {
            entity.setEnabled(GlobalConstant.ENABLED_YES);
            super.save(entity);
        } else {
            BlogMember blogMember = super.getById(params.getId());
            if (blogMember == null) {
                throw new DataNotFoundException();
            }
            // 判断图片是否为空
            if (StrUtil.isNotBlank(entity.getAvatar()) && !entity.getAvatar()
                    .startsWith("/" + fileService.getBucketName())) {
                FileUploadResult uploadResult = fileService
                        .putObject(URLUtil.getStream(URLUtil.url(entity.getAvatar())));
                if (uploadResult != null) {
                    entity.setAvatar(uploadResult.getPath());
                }
            }
            super.updateById(entity);
        }
        return entity;
    }

    @Override
    public BlogMember getByOpenId(String openId) {
        LambdaQueryWrapper<BlogMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BlogMember::getOpenId, openId);
        wrapper.eq(BlogMember::getEnabled, GlobalConstant.ENABLED_YES);
        return super.getOne(wrapper);
    }
}
